package com.taomeishu.mailcrazy.fetch.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.taomeishu.mailcrazy.fetch.CharseqNumberManger;
import com.taomeishu.mailcrazy.seq.CharseqNumber;

public class CharseqNumberMangerDAO extends JdbcDaoSupport implements CharseqNumberManger {

	@Override
	public CharseqNumber load(String id) {
		return (CharseqNumber)this.getJdbcTemplate().query("select id, content from mail_charseq where id = ?", new Object[] {id}, new ResultSetExtractor() {
			
			@Override
			public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
				if (!rs.next()) {
					return null;
				}
				CharseqNumber charseqNumber = new CharseqNumber(rs.getString("content"));
				return charseqNumber;
			}
		});
	}

	@Override
	public void save(String id, CharseqNumber charseqNumber) {
		CharseqNumber c = load(id);
		if (c != null) {
			// insert
			this.getJdbcTemplate().update("update mail_charseq set content =? , gmt_modified = now() where id = ?", new Object[] {charseqNumber.toCharSeqString(), id});
		} else {
			// update
			this.getJdbcTemplate().update("insert mail_charseq (id, content, gmt_create, gmt_modified) values(?, ?, now(), now())", new Object[] {id, charseqNumber.toCharSeqString()});
		}
	}

}
